package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/ylywyn/jpush-api-go-client"
	"huxiaopang/models"
	"net"
)

func pushData(storeCode string, tableCode string, tradeNo string){

	var deviceList []string
	var deviceListsSql string

	tradeData := models.TradeData{}
	tradeData.TradeNo = tradeNo
	if err := tradeData.Read("TradeNo"); err != nil {
		return
	} else {
		if(tradeData.HasPush == "Y"){
			//已经打印
			return	
		}
	}
	
	o := orm.NewOrm()
	deviceListsSql = fmt.Sprintf("SELECT reg_id from device_data WHERE device_id = (SELECT device_id from device_tablecode_data WHERE store_code = \"%s\" AND table_code = \"%s\")", storeCode, tableCode)
	beego.Debug(deviceListsSql)
	deviceListsNum, deviceListsErr := o.Raw(deviceListsSql).QueryRows(&deviceList)
	if deviceListsErr != nil || deviceListsNum <= 0 {
		return
	}
	beego.Debug(deviceList)

	//Platform
	var pf jpushclient.Platform
	pf.Add(jpushclient.ANDROID)
	//pf.Add(jpushclient.IOS)
	//pf.Add(jpushclient.WINPHONE)

	//Audience
	tags := []string{}
	alias := []string{}
	ids := deviceList
	var ad jpushclient.Audience
	ad.SetTag(tags)
	ad.SetAlias(alias)
	ad.SetID(ids)

	//Notice
	//var notice jpushclient.Notice
	//notice.SetAlert("alert_test")
	//notice.SetAndroidNotice(&jpushclient.AndroidNotice{Alert: "AndroidNotice"})
	//notice.SetIOSNotice(&jpushclient.IOSNotice{Alert: "IOSNotice"})
	//notice.SetWinPhoneNotice(&jpushclient.WinPhoneNotice{Alert: "WinPhoneNotice"})

	var msg jpushclient.Message
	msg.Title = "TradeNo"
	msg.Content = tradeNo

	payload := jpushclient.NewPushPayLoad()
	payload.SetPlatform(&pf)
	payload.SetAudience(&ad)
	payload.SetMessage(&msg)
	//payload.SetNotice(&notice)

	bytes, _ := payload.ToBytes()
	fmt.Printf("%s\r\n", string(bytes))

	//push
	c := jpushclient.NewPushClient(secret, appKey)
	str, err := c.Send(bytes)
	if err != nil {
		fmt.Printf("err:%s", err.Error())
	} else {
		fmt.Printf("ok:%s", str)
	}
}

func tcpPushData(storeCode string, deviceNum string, tradeNo string, randomStr string) {
	//2. 接受推送指令,短链接.....沪小胖后台使用.告诉我要推送.
	//指令: 0x51
	//入参:
	//store_code:xxxx
	//device_num:xxx
	//send_data:xxx
	//出参:
	//code: 0(成功) 1(失败)
	//msg: 具体描述信息

	if conn, err := net.Dial("tcp", "127.0.0.1:40060"); err != nil {
		beego.Debug("链接tcp服务器出错" + err.Error())
	} else {
		beego.Debug("tcp服务器连接成功")
		//发送
		if _, err := conn.Write(buildData(storeCode, deviceNum, tradeNo, randomStr)); err != nil {
			logs.Error(err.Error())
			conn.Close()
		} else {
			beego.Debug("send over")
			conn.Close()
		}
	}

}

func buildData(storeCode string, deviceNum string, tradeNo string, randomStr string) []byte {
	var pushDeviceData PushDeviceData
	pushDeviceData.StoreCode = storeCode
	pushDeviceData.DeviceNum = deviceNum
	pushDeviceData.SendData = tradeNo
	pushDeviceData.RandomStr = randomStr

	if data, err := json.Marshal(pushDeviceData); err != nil {
		logs.Error("发送失败:" + err.Error())
		return nil
	} else {
		//if len(data) >= 65535 {
		//	SENDCMDNAKTOOLONG(conn)
		//	return
		//}
		sendBytes := []byte{}
		sendBytes = append(sendBytes, 0xFF)
		sendBytes = append(sendBytes, 0xFF)
		sendBytes = append(sendBytes, 0x51)
		sendBytes = append(sendBytes, byte(uint16(len(data))>>8))
		sendBytes = append(sendBytes, byte(uint16(len(data))&0xFF))
		sendBytes = append(sendBytes, data...)
		sendBytes = append(sendBytes, 0xFF)
		sendBytes = append(sendBytes, 0xFE)
		beego.Debug(string(data))
		return sendBytes
	}
}

type PushDeviceData struct {
	StoreCode string `json:"store_code"`
	DeviceNum string `json:"device_num"`
	SendData  string `json:"send_data"`
	RandomStr  string `json:"random_str"`
}